#include "FileUtil.h"
#include <unistd.h>
#include <fstream>
#include <fstream>
#include <sstream>
#include <iostream>

namespace BASE{
	std::string FileUtil::joinFileName(const std::string & path, const std::string & fileName){
		std::string tmpPath = path;
		if (tmpPath[tmpPath.length() - 1] != '/'){
			tmpPath += '/';
		}
		tmpPath += fileName;
		return tmpPath;
	}

	Strings FileUtil::splitext(const std::string & fileName){
		Strings fileexts;
		size_t pos = fileName.find_last_of(".");
		if (pos == std::string::npos){
			fileexts.push_back(fileName);
		}else{
			fileexts.push_back(fileName.substr(0, pos));
			fileexts.push_back(fileName.substr(pos + 1));
		}
		return fileexts;
	}

	bool FileUtil::mkdirs(const std::string & path, mode_t mode){
		if (path.empty()){
			return false;
		}
		Strings strs = stringsplit(path, "/");
		Strings::iterator iter = strs.begin();
		std::string tmpPath = "/";
		for (; iter != strs.end(); ++iter){
			tmpPath += *iter;
			tmpPath += "/";
			std::cout << tmpPath << std::endl;
			if (FileUtil::exist(tmpPath)){
				continue;
			}
			std::cout << "mkdir " << tmpPath << std::endl;
			::mkdir(tmpPath.c_str(), mode);
		}
		return true;
	}

	bool FileUtil::unlink(const std::string & path){
		if (path.empty()){
			return false;
		}
		if (::unlink(path.c_str()) == 0){
			return true;
		}
		return false;
	}

	time_t FileUtil::getModifyTime(const std::string & fileName){
		if (fileName.empty()){
			return 0;
		}
		struct stat st;
		if (::stat(fileName.c_str(), &st) < 0){
			return 0;
		}
		return st.st_mtime;
	}

	uint64_t FileUtil::getSize(const std::string & fileName){
		if (fileName.empty()){
			return 0;
		}
		struct stat st;
		if (::stat(fileName.c_str(), &st) < 0){
			return 0;
		}
		return st.st_size;
	}

	bool FileUtil::exist(const std::string & fileName){
		if (fileName.empty()){
			return false;
		}
		struct stat st = {0};
		if (::stat(fileName.c_str(), &st) < 0){
			return false;
		}
		return true;
	}

	std::string FileUtil::readAll(const std::string & fileName){
		std::ifstream ifs(fileName.c_str(), std::ios::binary | std::ios::in);
		if (!ifs){
			return "";
		}
		std::stringstream ss;
		while(!ifs.eof()){
			char buf[8192];
			int n = ifs.readsome(buf, sizeof(buf));
			if (n <= 0){
				break;
			}
			ss.write(buf, n);
		}
		/*std::string line;
		while(!fs.eof()){
			std::getline(fs, line);
			std::cout << line << std::endl;
			ss << line << std::endl;
		}*/
		ifs.close();
		return ss.str();
	}

	bool FileUtil::writeAll(const std::string & fileName, const std::string & content){
		std::ofstream ofs(fileName.c_str(), std::ios::binary | std::ios::trunc);
		if (!ofs){
			return false;
		}
		ofs.write(content.c_str(), content.size());
		return true;
	}


}
